var BASE_URL = "http://192.168.10.24/wnsgbl-repo/mobileapp/mobile_api/";
var BASE_URL2 = "http://192.168.10.24/wnsgbl-repo/mobileapp/";
var token = "";
var error = "";
var user = "";
var cv = "";
var currentPage = 1;
var currentLatestJobsPage = 1;
var currentHighlightJobsPage = 1;

$(document).on("loadpanel","#latest", setupLatest);
$(document).on("loadpanel","#highlight", setupHighlight);
$(document).on("loadpanel","#application", setupApplication);

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.value = '-1';
  });
};

function login() {
    var username = $('#email').val();
    var password = $('#password').val();
    if (!username || !password) {
        $('#errorMessage').html = "Please fill Email and Password";
    } else {
        $.ajax({
            type:"POST",
            url:BASE_URL+"login",
            data:{username:username, password: password},
            success:function(jsonData){
                if (jsonData.status) {
                    token = jsonData.token;
                    user = jsonData.user;
                    localStorage.setItem('access_token', token);
                    localStorage.setItem('user', JSON.stringify(user));
                    $.ui.loadContent("#latest",false,false,"slide");
                } else {
                    error = jsonData.error;
                    $('#errorMessage').html = error;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }
}

function fill_data(panel, data, isAppend, isHighlight) {
    var list_html = "";
    if(data && data.length > 0) {
        for(var i=0; i< data.length; i++){
            var id = data[i].job_offerID;
            var name = data[i].job_offerTittle;
            //var img = data[i].mrc_logo;
            var descript = data[i].description;
            var company = data[i].companyName;
            var type_contract = data[i].type_contract;
            var min_salary_amount = data[i].min_salary_amount;
            var max_salary_amount = data[i].max_salary_amount;
            var currency_code = data[i].currency_code;
            var expired_date = data[i].expired_date;
            var duration_contract = data[i].duration_contract;


            //list_html += '<li><a href="#'+id+'"><h5>'+ name +'</h5><div>'+company+'</div><div>'+currency_code+' '+min_salary_amount+' - '+max_salary_amount+'</div></a></li>';
            
            list_html += '<li><a href="#" onclick="openJobDetail(\''+id+'\');"><h5>'+ name +'</h5><div>'+company+'</div><div>'+currency_code+' '+min_salary_amount+' - '+max_salary_amount+'</div></a></li>';

            /* Dynamically add panel */
            var panel_content = '<h2>'+name+'</h2><p>'+descript+'</p><p>Expired data: '+expired_date+'<br/><br/><h3>Company Info</h3><table class="table-description"><tr><td>Company Name</td><td>'+company+'</td></tr><tr><td>Company Size</td><td>'+data[i].company_size+'</td></tr><tr><td>Company Description</td><td>'+data[i].companyDesc+'</td></tr></table><br/><h3>Candidate Requirements</h3><table class="table-description"><tr><td>Minimum Studies</td><td>'+data[i].min_studies_candidate+'</td></tr><tr><td>Speciality</td><td>'+data[i].specialty_studies+'</td></tr><tr><td>Minimum Experience</td><td>'+data[i].minimum_experience+'</td></tr><tr><td>Necessary knowledge</td><td>'+data[i].neccesary_knowledge+'</td></tr><tr><td>Other requirements</td><td>'+data[i].other_requirement+'</td></tr></table><br/><h3>Other Info</h3><table class="table-description"><tr><td>Contract Type</td><td>'+type_contract+'</td></tr><tr><td>Contract Duration</td><td>'+duration_contract+'</td></tr><tr><td>Position Level</td><td>'+data[i].position_level+'</td></tr><tr><td>Staff in charge</td><td>'+data[i].staff_in_charge+'</td></tr><tr><td>Category</td><td>'+data[i].job_categoryName+', '+data[i].job_subcategoryName+'</td></tr><tr><td>Location</td><td>'+data[i].state_name+', '+data[i].country_name+'</td></tr><tr><td>Number of Vacancies</td><td>'+data[i].number_vacancies+'</td></tr></table><a id="applyJob" onclick="openApply(\''+id+'\');" class="button" style="width: 100%;" >Apply</a>';
            //$.ui.addContentDiv(id, panel_content, "Job Detail"); 
        }
        if (isAppend) {
            $("#"+panel).append(list_html);
        } else {
            $("#"+panel).html(list_html);
        }
        if (isAppend && isHighlight && isAppend) {
            currentHighlightJobsPage++;
        } else if (isAppend && !isHighlight && isAppend) {
            currentLatestJobsPage++;
        }
    }
}

function get_latest_jobs(page, isAppend, scroller, isRefresh) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"jobs",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{page: page},
        success:function(data){
            //$('#latestDiv').html(data);
            fill_data("latestJobList", data, isAppend, false);
            if (null == scroller) {
                if (isRefresh) {
                    scroller.hideRefresh();
                } else {
                    scroller.clearInfinite();
                }
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
            if (null == scroller) {
                if (isRefresh) {
                    scroller.hideRefresh();
                } else {
                    scroller.clearInfinite();
                }
            }
            /*if (xhr.status == 401) {
                $.ui.loadContent("#select",false,false,"up");
            }*/
        }
    });
}

function get_highlight_jobs(page, isAppend, scroller, isRefresh) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"highlight_jobs",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{page: page},
        success:function(data){
            fill_data("highlightJobList", data, isAppend, true);
            if (null == scroller) {
                if (isRefresh) {
                    scroller.hideRefresh();
                } else {
                    scroller.clearInfinite();
                }
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (null == scroller) {
                if (isRefresh) {
                    scroller.hideRefresh();
                } else {
                    scroller.clearInfinite();
                }
            }
            /*if (xhr.status == 401) {
                $.ui.loadContent("#select",false,false,"up");
            }*/
        }
    });
}

/*function resizeMap(){
    $("#maps").gmaps("resize");
}*/

/* Google Maps API code to show map and layers */        
        
var map;
function setupMap(){
    var mapOptions = {
        center: new google.maps.LatLng(45.53, -122.67),
        zoom: 10,
        mapTypeControl: false,
        streetViewControl: false,
        navigationControl: true,
        scrollwheel: false,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    try{
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    }catch(err){
        alert(err);
    }
}
        
function getGeoLocation(){
    var success = function(position){
        map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, null);
    }   
}       
/*var trafficLayer = new google.maps.TrafficLayer();
var transitLayer = new google.maps.TransitLayer();        
var bicyclingLayer = new google.maps.BicyclingLayer();
function toggleTrafficLayer(){
    document.getElementById('toggle1').checked ? trafficLayer.setMap(map) : trafficLayer.setMap(null);
} 
        
function toggleTransitLayer(){
    document.getElementById('toggle2').checked ? transitLayer.setMap(map) : transitLayer.setMap(null);
} 
        
function toggleBicyclingLayer(){
    document.getElementById('toggle3').checked ? bicyclingLayer.setMap(map) : bicyclingLayer.setMap(null);
}*/

// enable pullToRefresh and infiniteScroll to listview (af.scroller.js)
function setupListUpdate(panel, list, isHighlight) {
    $.ui.ready(function () {
        var scrollerList = $("#"+panel).scroller();

        scrollerList.addPullToRefresh();
        $.bind(scrollerList, "refresh-release", function () {
            if (isHighlight) {
                currentHighlightJobsPage = 1;
            } else {
                currentLatestJobsPage = 1;
            }
            if (isHighlight) {
                get_highlight_jobs(currentHighlightJobsPage, false, this, true);
            } else {
                get_latest_jobs(currentLatestJobsPage, false, this, true);
            }

            return false; //tells it to not auto-cancel the refresh
        });

        scrollerList.addInfinite();
        $.bind(scrollerList, "infinite-scroll", function () {
            $("#"+panel).find("#"+list).html('Load more..');
            var goToPage = 1;
            if (isHighlight) {
                goToPage = currentHighlightJobsPage + 1;
            } else {
                goToPage = currentLatestJobsPage + 1;
            }
            
            if (isHighlight) {
                get_highlight_jobs(goToPage, false, this, true);
            } else {
                get_latest_jobs(goToPage, false, this, true);
            }

        });

        scrollerList.enable();
    });
}

var latestUnloaded = true;
function setupLatest() {
    if (latestUnloaded) {
        setupListUpdate("latest", "infiniteLatest", false);
        
        get_latest_jobs(currentLatestJobsPage, false, null, true);
        
        latestUnloaded = false;
    }
}

var highlightUnloaded = true;
function setupHighlight() {
    if (highlightUnloaded) {
        setupListUpdate("highlight", "infiniteHighlight", true);
        get_highlight_jobs(currentHighlightJobsPage, false, null, true);
        highlightUnloaded = false;
    }
}

var currencies = [];
function get_currencies(element) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"currencies",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        //data:{page: page},
        success:function(data){
            currencies = data;
            set_currencies(element, data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            
        }
    });
}

function set_currencies(element, data) {
    $('#'+element).html('');
    for(var i=0; i< data.length; i++){
        $('#'+element).append('<option value='+data[i].currency_id+'>'+data[i].currency_code+'</option>');
    }
}

var educations = [];
function get_educations(userID) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"educations",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{userID: userID},
        success:function(data){
            educations = data;
            $('#educationList').html('');
            for(var i=0; i< educations.length; i++){
                $('#educationList').append('<li><a href="#" onclick="openEducationDetail(\''+educations[i].educationID+'\');">'+educations[i].institute_name+'</a></li>');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}

var experiences = [];
function get_experiences(userID) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"experiences",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{userID: userID},
        success:function(data){
            experiences = data;
            set_experience_list(experiences);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}

var knowledges = [];
function get_knowledges(userID) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"knowledges",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{userID: userID},
        success:function(data){
            knowledges = data;
            set_knowledge_list(knowledges);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}

var countries = [];
function get_countries() {
    $.ajax({
        type:"GET",
        url:BASE_URL+"countries",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        //data:{userID: userID},
        success:function(data){
            countries = data;
            $('#country_id').html('');
            $('#country_id').append('<option value="-1">[Country]</option>');
            for(var i=0; i< countries.length; i++){
                $('#country_id').append('<option value='+countries[i].country_id+'>'+countries[i].country_name+'</option>');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            
        }
    });
}

function set_experience_list(experiences) {
    $('#experienceList').html('');
    for(var i=0; i< experiences.length; i++){
        $('#experienceList').append('<li><a href="#" onclick="openExperienceDetail(\''+experiences[i].work_experienceID+'\');">'+experiences[i].title+'</a></li>');
    }
}

function set_knowledge_list(knowledges) {
    $('#knowledgeList').html('');
    for(var i=0; i< knowledges.length; i++){
        $('#knowledgeList').append('<li><a href="#" onclick="openKnowledgeDetail(\''+knowledges[i].knowledgeID+'\');">'+knowledges[i].knowledge+'</a></li>');
    }
}

function get_cv(userID) {
    return $.ajax({
        type:"GET",
        url:BASE_URL+"cv",
        data:{userID:userID}
        /*,
        success:function(jsonData){
            if (jsonData) {
                cv = jsonData;
                localStorage.setItem('cv', JSON.stringify(jsonData));
                var userObject = JSON.parse(localStorage.getItem('user'));
                set_personal_data(cv, userObject);
            } else {
                //error = jsonData.error;
                //$('#errorMessage').html = error;
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }*/
    });
}

function setupCV() {
    if (!cv) {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_cv(userObject.userID).done(function(data) {
            if (jsonData) {
                cv = jsonData;
                localStorage.setItem('cv', JSON.stringify(jsonData));
                var userObject = JSON.parse(localStorage.getItem('user'));
                set_personal_data(cv, userObject);
            }
        });
    }
    if (null == educations || educations.length === 0) {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_educations(userObject.userID);
    } else {
        $('#educationList').html('');
        for(var i=0; i< educations.length; i++){
            $('#educationList').append('<li><a href="#" onclick="openEducationDetail(\''+educations[i].educationID+'\');">'+educations[i].institute_name+'</a></li>');
        }
    }
    if (null == experiences || experiences.length === 0) {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_experiences(userObject.userID);
    } else {
        set_experience_list(experiences);
    }
    if (null == knowledges || knowledges.length === 0) {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_knowledges(userObject.userID);
    } else {
        set_knowledge_list(knowledges);
    }
    
    if (null == countries || countries.length === 0) {
        get_countries();
    } else {
        if ($('#country_id').html().length > 0) {
            
        } else {
            $('#country_id').html('');
            $('#country_id').append('<option value="-1">[Country]</option>');
            for(var i=0; i< countries.length; i++){
                $('#country_id').append('<option value='+countries[i].country_id+'>'+countries[i].country_name+'</option>');
            }
        }
    }
}

function setupPersonal() {
    if (null == currencies || currencies.length === 0) {
        get_currencies('currency');
    } else {
        set_currencies('currency', currencies);
    }
}

function setupEducation() {
}

function setupExperience() {
    if (null == currencies || currencies.length === 0) {
        get_currencies('exp_currency_id');
    } else {
        set_currencies('exp_currency_id', currencies);
    }
}

function openEducationDetail(eduId) {
    if (eduId) {
        $.ajax({
            type:"GET",
            url:BASE_URL+"educationdetails",
            headers:{'X-Auth-Token':localStorage.getItem('access_token')},
            data:{educationID: eduId},
            success:function(data){
                $("#education_detail_form")[0].reset();
                if (null != data) {
                    $('#education_detail_form').loadJSON(data);
                    $('#education_detail_form').find('[name="qualification"]').val(data.qualification);
                    $('#education_detail_form').find('[name="field_of_study"]').val(data.field_of_study);
                    $('#education_detail_form').find('[name="graduation_date"]').val(data.graduation_date);
                    $('#education_detail_form').find('[name="country_id"]').val(data.country_id);
                    $.ui.loadContent("#education_detail",false,false,"up");                    
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });
    } else {
        $("#education_detail_form").clearForm();
        $('#education_detail_form').find('[name="graduation_date"]').val('');
        $.ui.loadContent("#education_detail",false,false,"up");
    }
}

function openExperienceDetail(id) {
    if (id) {
        $.ajax({
            type:"GET",
            url:BASE_URL+"experience",
            headers:{'X-Auth-Token':localStorage.getItem('access_token')},
            data:{work_experienceID: id},
            success:function(data){
                $("#experience_detail_form")[0].reset();
                if (null != data) {
                    $('#experience_detail_form').loadJSON(data);
                    //alert(data.salary_type_period);
                    $('#experience_detail_form').find('[name="salary_type_period"]').val(data.salary_type_period);
                    $('#experience_detail_form').find('[name="currency_id"]').val(data.currency_id);
                    $('#experience_detail_form').find('[name="staff_in_charge"]').val(data.staff_in_charge);
                    $('#experience_detail_form').find('[name="starting_date"]').val(data.starting_date);
                    $('#experience_detail_form').find('[name="ending_date"]').val(data.ending_date);
                    if (data.show_salary && data.show_salary === "1") {
                        $('#experience_detail_form').find('[name="show_salary"]').prop('checked', true);
                    } else {
                        $('#experience_detail_form').find('[name="show_salary"]').prop('checked', false);
                    }
                    
                    if (data.ending_date && data.ending_date === "0000-00-00") {
                        $('#experience_detail_form').find('[name="present"]').prop('checked', true);
                        $('#endingDateDiv').hide();
                    } else {
                        $('#experience_detail_form').find('[name="present"]').prop('checked', false);
                        $('#endingDateDiv').show();
                    }
                    $.ui.loadContent("#experience_detail",false,false,"up");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });
    } else {
        $("#experience_detail_form").clearForm();
        var cvObject = JSON.parse(localStorage.getItem('cv'));
        $('#experience_detail_form').find('[name="cv_id"]').val(cvObject.cvID);
        $('#experience_detail_form').find('[name="starting_date"]').val('');
        $('#experience_detail_form').find('[name="ending_date"]').val('');
        $.ui.loadContent("#experience_detail",false,false,"up");
    }
}

function openKnowledgeDetail(id) {
    if (id) {
        $.ajax({
            type:"GET",
            url:BASE_URL+"knowledge",
            headers:{'X-Auth-Token':localStorage.getItem('access_token')},
            data:{knowledgeID: id},
            success:function(data){
                $("#knowledge_detail_form")[0].reset();
                if (null != data) {
                    $('#knowledge_detail_form').loadJSON(data);
                    $('#knowledge_detail_form').find('[name="level"]').val(data.level);
                    $.ui.loadContent("#knowledge_detail",false,false,"up");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });
    } else {
        $("#knowledge_detail_form").clearForm();
        var userObject = JSON.parse(localStorage.getItem('user'));
        $('#knowledge_detail_form').find('[name="userID"]').val(userObject.userID);
        $.ui.loadContent("#knowledge_detail",false,false,"up");
    }
}

function openPersonal() {
    if(localStorage.getItem('cv')) {
        var cvObject = JSON.parse(localStorage.getItem('cv'));
        var userObject = JSON.parse(localStorage.getItem('user'));
        set_personal_data(cvObject, userObject);
    } else {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_cv(userObject.userID).done(function(data) {
            if (jsonData) {
                cv = jsonData;
                localStorage.setItem('cv', JSON.stringify(jsonData));
                var userObject = JSON.parse(localStorage.getItem('user'));
                set_personal_data(cv, userObject);
            }
        });
    }
    $.ui.loadContent("#personal",false,false,"up");
}

function set_personal_data(cvData, userData) {
    $('#personal_form').loadJSON(cvData);
    $('#personal_form').find('[name="displayName"]').val(userData.displayName);
    $('#personal_form').find('[name="birthDate"]').val(userData.birthDate);
    $('#personal_form').find('[name="gender"]').val(userData.gender);
    $('#personal_form').find('[name="address1"]').val(userData.address1);
    $('#personal_form').find('[name="phone"]').val(userData.phone);
    $('#personal_form').find('[name="experience_years"]').val(cvData.experience_years);     //$('#profilePic').attr("src","http://www.wallpaperhi.com/thumbnails/detail/20120705/men%20people%20christian%20bale%20actors%20faces%202021x3000%20wallpaper_www.wallpaperhi.com_26.jpg");
    $('#profilePic').attr("src",userData.avatar);
}

function logout() {
    //localStorage.setItem('access_token', null);
    //localStorage.setItem('user', null);
    localStorage.removeItem('access_token');
    localStorage.removeItem('user');
    $.ui.loadContent("#select",false,false,"up");
}

function saveEducation() {
    $.ajax({
        type:"POST",
        url:BASE_URL+"education",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:$("#education_detail_form").serialize(),
        success:function(data){
            var userObject = JSON.parse(localStorage.getItem('user'));
            get_educations(userObject.userID);
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function saveExperience() {
    $.ajax({
        type:"POST",
        url:BASE_URL+"experience",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:$("#experience_detail_form").serialize(),
        success:function(data){
            var userObject = JSON.parse(localStorage.getItem('user'));
            get_experiences(userObject.userID);
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function saveKnowledge() {
    $.ajax({
        type:"POST",
        url:BASE_URL+"knowledge",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:$("#knowledge_detail_form").serialize(),
        success:function(data){
            var userObject = JSON.parse(localStorage.getItem('user'));
            get_knowledges(userObject.userID);
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function untilNowChange() {
    var checked = $('#until_now').is(':checked');
    try{
    if (checked) {
        $('#endingDateDiv').hide();
    } else {
        $('#endingDateDiv').show();
    }
    }catch(exc){
        alert(exc);
    }
}

function saveCV() {
    $.ajax({
        type:"POST",
        url:BASE_URL+"cv",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:$("#personal_form").serialize(),
        success:function(data){
            //var userObject = JSON.parse(localStorage.getItem('user'));
            //get_educations(userObject.userID);
            user = data.user;
            cv = data.cv;
            localStorage.setItem('user', JSON.stringify(user));
            localStorage.setItem('cv', JSON.stringify(cv));
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function uploadFromGallery() {
    var deviceType = (navigator.userAgent.match(/iPad/i))  == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i))  == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";

    if (deviceType === 'Android') {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(uploadPhoto,
                                    function(message) {  },
                                    { quality: 50, 
                                    destinationType: navigator.camera.DestinationType.FILE_URI,
                                    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                                    );
    } else {
        document.getElementById('image_file').click();
    }
}

function uploadPhoto(imageURI) {
    //alert(imageURI);
    window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
            //alert(fileEntry.name + " " +fileEntry.fullPath);
        fileEntry.file(function(filee) {
            //alert(filee.type); //THIS IS MIME TYPE
            var options = new FileUploadOptions();  
            options.fileKey="image_file";
            options.fileName=fileEntry.name;
            options.mimeType=filee.type;

            var params = new Object();
            var userObject = JSON.parse(localStorage.getItem('user'));
            params.userID = userObject.userID;

            options.params = params;

            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI(BASE_URL2+'profile_pic'), win, fail, options);
        }, function() {
            //alert('error');
        });


    }, onError);
    /*
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
    options.mimeType="text/plain";

    var params = new Object();
    var userObject = JSON.parse(localStorage.getItem('user'));
    params.userID = userObject.userID;

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI(BASE_URL2+'profile_pic'), win, fail, options);
    */
}

function onError() {
    alert('fehler resolve file system');
}

function win(r) {
    //alert("Response = " + r.response);
    var data = r.response;
    var jsonObject = JSON.parse(data);
    $('#profilePic').attr("src",jsonObject.full_path);
    var userObject = JSON.parse(localStorage.getItem('user'));
    userObject.avatar = jsonObject.full_path;
    localStorage.setItem('user', JSON.stringify(userObject));
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}

function uploadOption() {
    //$.ui.actionsheet("<a href='javascript:;' class='button'>Settings</a> <a href='javascript:;' class='button red'>Logout</a>");
    //$.ui.actionsheet("Settings Logout");
    //$(document.body).actionsheet('<a  onclick="alert(\'hi\');" >Hi</a><a  onclick="alert(\'goodbye\');">Goodbye</a>');
    $("#afui").actionsheet('<a  >Back</a><a  onclick="alert(\'hi\');" >Show Alert 3</a><a  onclick="alert(\'goodbye\');">Show Alert 4</a>');
 
}

function openApply(id) {
    $("#apply_form").clearForm();
    $('#apply_form').find('[name="job_offerID"]').val(id);
    var userObject = JSON.parse(localStorage.getItem('user'));
    $('#apply_form').find('[name="userID"]').val(userObject.userID);
    if (!cv) {
        var userObject = JSON.parse(localStorage.getItem('user'));
        get_cv(userObject.userID).done(function(jsonData) {
            if (jsonData) {
                cv = jsonData;
                localStorage.setItem('cv', JSON.stringify(jsonData));
                var userObject = JSON.parse(localStorage.getItem('user'));
                set_personal_data(cv, userObject);
                $('#apply_form').find('[name="cvID"]').val(cv.cvID);
                $.ui.loadContent("#apply_job",false,false,"up");
            }
        });
    } else {
        $('#apply_form').find('[name="cvID"]').val(cv.cvID);
        $.ui.loadContent("#apply_job",false,false,"up");
    }
}

function submitApplication() {
    $.ajax({
        type:"POST",
        url:BASE_URL+"apply",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:$("#apply_form").serialize(),
        success:function(data){
            if (data === 'ok') {
                $.ui.goBack();
            } else if (data === 'allready') {
                alert('You have already applied for this job');
            } else if (data === 'nocv') {
                alert('You have not filled your CV, please fill it first on CV page');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function setupApplication() {
    var userObject = JSON.parse(localStorage.getItem('user'));
    get_applications(userObject.userID);
}

function get_applications(userID) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"applications",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{userID: userID},
        success:function(data){
            var list_html = "";
            if(data && data.length > 0) {
                for(var i=0; i< data.length; i++){
                    var panel_content = '';
                    if (data[i].deleted === '0') {
                        list_html += '<li><a href="#'+data[i].offer_applyID+'"><h5>'+ data[i].job_offerTittle +'</h5><div>'+data[i].companyName+'</div><div>'+data[i].status+'</div></a></li>';

                        /* Dynamically add panel */
                        panel_content = '<h2>'+data[i].job_offerTittle+'</h2><p>'+data[i].companyName+'</p><p>Date of Apply: '+data[i].date_of_apply+'<a id="withdrawButton" onclick="withdraw(\''+data[i].offer_applyID+'\', \''+data[i].job_offerID+'\')" class="button" style="width: 100%;" ><i class="icon fa-trash-o"></i> Withdraw</a>';
                    } else {
                        list_html += '<li><a href="#'+data[i].offer_applyID+'"><h5><del>'+ data[i].job_offerTittle +'</del></h5><div>'+data[i].companyName+'</div><div>'+data[i].status+'</div></a></li>';

                        /* Dynamically add panel */
                        panel_content = '<h2>'+data[i].job_offerTittle+'</h2><p>'+data[i].companyName+'</p><p>Date of Apply: '+data[i].date_of_apply+'<a id="withdrawButton" onclick="reapply(\''+data[i].offer_applyID+'\', \''+data[i].job_offerID+'\')" class="button" style="width: 100%;" >Reapply</a>';
                    }
                    
                    $.ui.addContentDiv(data[i].offer_applyID, panel_content, "Application Detail"); 
                }
                
                $("#applicationList").html(list_html);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function withdraw(offer_applyID, job_offerID) {
    $.ajax({
        type:"POST",
        url:BASE_URL+"withdraw",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{offer_applyID:offer_applyID, job_offerID:job_offerID},
        success:function(data){
            var userObject = JSON.parse(localStorage.getItem('user'));
            get_applications(userObject.userID);
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function reapply(offer_applyID, job_offerID) {
    $.ajax({
        type:"POST",
        url:BASE_URL+"reapply",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{offer_applyID:offer_applyID, job_offerID:job_offerID},
        success:function(data){
            var userObject = JSON.parse(localStorage.getItem('user'));
            get_applications(userObject.userID);
            $.ui.goBack();
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function openJobDetail(id) {
    $.ajax({
        type:"GET",
        url:BASE_URL+"job",
        headers:{'X-Auth-Token':localStorage.getItem('access_token')},
        data:{job_offerID:id},
        success:function(data){
            setJobDetail(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

function setJobDetail(data) {
    var id = data.job_offerID;
    var name = data.job_offerTittle;
    //var img = data[i].mrc_logo;
    var descript = data.description;
    var company = data.companyName;
    var type_contract = data.type_contract;
    var min_salary_amount = data.min_salary_amount;
    var max_salary_amount = data.max_salary_amount;
    var currency_code = data.currency_code;
    var expired_date = data.expired_date;
    var duration_contract = data.duration_contract;
    
    var panel_content = '<h2>'+name+'</h2><p>'+descript+'</p><p>Expired data: '+expired_date+'<br/><br/><h3>Company Info</h3><table class="table-description"><tr><td>Company Name</td><td>'+company+'</td></tr><tr><td>Company Size</td><td>'+data.company_size+'</td></tr><tr><td>Company Description</td><td>'+data.companyDesc+'</td></tr></table><br/><h3>Candidate Requirements</h3><table class="table-description"><tr><td>Minimum Studies</td><td>'+data.min_studies_candidate+'</td></tr><tr><td>Speciality</td><td>'+data.specialty_studies+'</td></tr><tr><td>Minimum Experience</td><td>'+data.minimum_experience+'</td></tr><tr><td>Necessary knowledge</td><td>'+data.neccesary_knowledge+'</td></tr><tr><td>Other requirements</td><td>'+data.other_requirement+'</td></tr></table><br/><h3>Other Info</h3><table class="table-description"><tr><td>Contract Type</td><td>'+type_contract+'</td></tr><tr><td>Contract Duration</td><td>'+duration_contract+'</td></tr><tr><td>Position Level</td><td>'+data.position_level+'</td></tr><tr><td>Staff in charge</td><td>'+data.staff_in_charge+'</td></tr><tr><td>Category</td><td>'+data.job_categoryName+', '+data.job_subcategoryName+'</td></tr><tr><td>Location</td><td>'+data.state_name+', '+data.country_name+'</td></tr><tr><td>Number of Vacancies</td><td>'+data.number_vacancies+'</td></tr></table><a id="applyJob" onclick="openApply(\''+id+'\');" class="button" style="width: 100%;" >Apply</a>';
            
    $.ui.updateContentDiv("#jobDetail",panel_content);
                        
    $.ui.loadContent("#jobDetail",false,false,"slide");
}